package cn.bgs.controller;

import cn.bgs.pojo.*;
import cn.bgs.service.StuReService;
import cn.bgs.service.StuService;
import cn.bgs.utils.ExcelReader;
import cn.bgs.utils.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;


@Controller
@RequestMapping("/stu")
public class StuController {

    Logger log = LogManager.getLogger();

    @Autowired
    private StuService stuService;

    @Autowired
    private StuReService stuReService;


    //全查
//    @RequestMapping("/findAllStu")
//    public String findAllStu(Student stu,Model mo){
//        List<Student> allStu = stuService.findAllStu(stu);
//        System.err.println(allStu);
//        mo.addAttribute("stu",allStu);
//        return "userlist";
//    }


    //导出数据库至excel
//    @RequestMapping("/export")
//    public String export(){
//        String excel="D:\\Email\\stuExcel.xlsx";//设定读取Exce表的路径
//
//        List<Student> list = stuService.stuExcel();
//
//        Workbook sheets = ExcelWriter.exportData(list);//转换写入Excel表的数据
//        FileOutputStream fileOut = null;
//
//        try{
//            File exportFile = new File(excel);
//            if (!exportFile.exists()) {
//                exportFile.createNewFile();
//            }
//            fileOut = new FileOutputStream(excel);
//            sheets.write(fileOut);
//            fileOut.flush();
//        }catch (Exception e){
//            System.out.println("输出时出现错误"+e.getMessage());
//        }finally {
//            try {
//                if (null != fileOut) {
//                    fileOut.close();
//                }
//                if (null != sheets) {
//                    sheets.close();
//                }
//            } catch (IOException e) {
//                System.out.println("关闭输出流时发生错误，错误原因：" + e.getMessage());
//            }
//        }
//        return "/view/stushow";
//    }

    //导出数据库至excel
    @RequestMapping("/export")
    @ResponseBody
    public String export(){
        return stuService.stuExcel();
    }


//    //excel导入至数据库
//    @RequestMapping("/import")
//    public String ExcelReader(MultipartFile multipartFile , Model m) throws IOException{
//        String file=multipartFile.getOriginalFilename();
//        String uuid = UUID.randomUUID().toString();//解决名称重复问题，用UUID来解决
//        String replace = uuid.replace("-","");//去掉小横杠
//        String name= replace.toUpperCase();//全部变大写
//        int lastIndex=file.lastIndexOf(".");//找到原文件的后缀，先找.最后出现的位置
//        String suffix = file.substring(lastIndex);//截取.后面的全部名称
//        String newName=name+suffix;//组成永不重复的新的文件名称
//        multipartFile.transferTo(new File("D:\\Email\\"+newName));//上传文件，把文件存入文件系统
//        List<Student> readResult = ExcelReader.readExcel("D:\\Email\\"+newName);
//        System.out.println("list::::::::::::::::::::"+readResult);
//            log.info("Student:::::::::::::: " + readResult);
//            stuService.addStu(readResult);
//            StudentRegister sture  = new StudentRegister();
//            sture.setStuNum(sture.getStuNum());
//            sture.setEmail(sture.getEmail());
//            sture.setPassword(sture.getPassword());
//            sture.setStatus("0");
//            sture.setDeleteFlag("0");
//            Calendar now = Calendar.getInstance();//获取时间
//            sture.setCreateTime(now.getTime());
//            sture.setUpdateTime(now.getTime());
//            stuReService.addStuRe(sture);
//        m.addAttribute("success" , "导入成功");
//        return "/view/stushow";
//    }

    //excel导入至数据库
    @RequestMapping("/import")
    public String importt(){
        // 设定Excel文件所在路径
        String excelFileName = "D:\\Email\\importExcel.xlsx";
        // 读取Excel文件内容
        List<Student> readResult = ExcelReader.readExcel(excelFileName);
        for (int i = 0; i < readResult.size(); i++) {
            System.err.println("qweqweqweqweqweqwe"+readResult.get(i).toString());
        }
        stuService.addStu(readResult);
        return "/view/stushow";
    }

    //跳转学生管理
    @RequestMapping("/a")
    public String a(){
        return "/view/stushow";
    }

    //跳转添加页面
//    @RequestMapping("/add")
//    public String add(){
//        return "stuadd";
//    }

//    //全查 ajax
//    @RequestMapping("/findAllStu")
//    @ResponseBody
//    public List<Student> findAllStu(){
//        List<Student> allStu = stuService.findAllStu();
////        System.err.println(allStu);
////        mo.addAttribute("stu",allStu);
//        return allStu;
//    }

    //模糊查询
//    @RequestMapping("/fuzzyQueryStu")
//    public String fuzzyQueryStu(StudentVo stu, Model mo){
//        List<StudentVo> students = stuService.fuzzyQueryStu(stu);
////        System.err.println(students);
//        mo.addAttribute("stu",students);
//        return "userlist";
//    }





    //删除
    @RequestMapping("/delStu")
    @ResponseBody
    public boolean delStu(@RequestBody String id){
        JSONObject json = JSONObject.parseObject(id);
        Integer stuId = Integer.parseInt(json.getString("stuId"));
        return stuService.delStu(stuId);
    }

    //查询修改
    @RequestMapping("/selOneStu")
    @ResponseBody
    public Student selOneStu(@RequestBody String id){
        JSONObject jsonObject = JSONObject.parseObject(id);
        Integer stuId = Integer.parseInt(jsonObject.getString("stuId"));
        return stuService.selOneStu(stuId);
    }

    //修改
    @RequestMapping("/updateStu")
    @ResponseBody
    public Integer updateStu(@RequestBody String stu){
        JSONObject jsonObject = JSONObject.parseObject(stu);
        Student ss = new Student();
        ss.setStuId(Integer.parseInt(jsonObject.getString("stuId")));
        ss.setStuName(jsonObject.getString("stuName"));
        ss.setMobile(jsonObject.getString("mobile"));
        ss.setSex(jsonObject.getString("sex"));
        ss.setIdType(jsonObject.getString("idType"));
        ss.setIdNum(jsonObject.getString("idNum"));
        ss.setBirthday(jsonObject.getDate("birthday"));
        ss.setProvincesId(Integer.parseInt(jsonObject.getString("provincesId")));
        ss.setCitiesId(Integer.parseInt(jsonObject.getString("citiesId")));
        ss.setAreasId(Integer.parseInt(jsonObject.getString("areasId")));
        ss.setDetailAddr(jsonObject.getString("detailAddr"));
        Calendar now = Calendar.getInstance();//获取时间

        ss.setUpdateDate(now.getTime());
        return stuService.updateStu(ss);
    }

    //添加
    @RequestMapping("/insertStu")
    @ResponseBody
    public Integer insertStu(@RequestBody String inStu){
        JSONObject jsonObject = JSONObject.parseObject(inStu);
        Student ss = new Student();
        ss.setStuNum(Integer.parseInt(jsonObject.getString("stuNum")));
        ss.setStuName(jsonObject.getString("stuName"));
        ss.setMobile(jsonObject.getString("mobile"));
        ss.setSex(jsonObject.getString("sex"));
//        ss.setAge(Integer.parseInt(jsonObject.getString("age")));
        ss.setIdType(jsonObject.getString("idType"));
        ss.setIdNum(jsonObject.getString("idNum"));
        ss.setBirthday(jsonObject.getDate("birthday"));
        ss.setProvincesId(Integer.parseInt(jsonObject.getString("provincesId")));
        ss.setCitiesId(Integer.parseInt(jsonObject.getString("citiesId")));
        ss.setAreasId(Integer.parseInt(jsonObject.getString("areasId")));
        ss.setDetailAddr(jsonObject.getString("detailAddr"));
        ss.setDeleteFlag(0);
        Calendar now = Calendar.getInstance();//获取时间

        ss.setCreateDate(now.getTime());
        ss.setUpdateDate(now.getTime());

//        System.err.println("添加数据：：：：：：：：：：：：：：：：："+ss);
        return  stuService.insertStu(ss);
    }

    //查询省
    @RequestMapping("/selPro")
    @ResponseBody
    public List<Provinces> selPro(){
        return stuService.selPro();
    }
    //查询市
    @RequestMapping("/selCity")
    @ResponseBody
    public List<Cities> selCity(){
        return stuService.selCity();
    }
    //查询县
    @RequestMapping("/selArea")
    @ResponseBody
    public List<Areas> selArea(){
        return stuService.selArea();
    }

    //全查  stushow
    @ResponseBody
    @RequestMapping("/findAllStu")
    public Map<String,Object> findAllStu(@RequestParam(required=false,defaultValue="1") int page,
                                          @RequestParam(required=false,defaultValue="7") int limit,
                                          String stuName, String mobile, String sex, Integer age, String idNum){
        // 使用Pagehelper传入当前页数和页面显示条数会自动为我们的select语句加上limit查询
        // 从他的下一条sql开始分页
        PageHelper.startPage(page, limit);
        List<Student> stu  = stuService.findAllStu(stuName,mobile,sex,age,idNum);// 这是我们的sql
        for(Student i:stu){
            i.setNativePlace(i.getNativePlace());
        }

//        log.info("data_______:::::"+stu);
//        log.info("String studentName, String mobile, String sex,Integer age,String idNum：：：：：：："
//                +stuName+"   "
//                +mobile+"   "
//                +sex+"   "
//                +age+"   "
//                +idNum+"   "
//        );
        // 使用pageInfo包装查询
        PageInfo<Student> rolePageInfo = new PageInfo<>(stu);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",rolePageInfo.getTotal());
        map.put("data",rolePageInfo.getList());
        log.info("map------------------------------------"+map);
        return map;
    }


    //宿舍中添加学生需要的学生名单
    @ResponseBody
    @RequestMapping("/addDormStu")
    public Map<String,Object> addDormStu(@RequestParam(required=false,defaultValue="1") int page,
                                         @RequestParam(required=false,defaultValue="7") int limit
                                         ){
        // 使用Pagehelper传入当前页数和页面显示条数会自动为我们的select语句加上limit查询
        // 从他的下一条sql开始分页
        PageHelper.startPage(page, limit);
        List<Student> stu  = stuService.addDormStu();// 这是我们的sql
        for(Student i:stu){
            i.setNativePlace(i.getNativePlace());
        }

//        log.info("data_______:::::"+stu);
//        log.info("String studentName, String mobile, String sex,Integer age,String idNum：：：：：：："
//                +stuName+"   "
//                +mobile+"   "
//                +sex+"   "
//                +age+"   "
//                +idNum+"   "
//        );
        // 使用pageInfo包装查询
        PageInfo<Student> rolePageInfo = new PageInfo<>(stu);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",rolePageInfo.getTotal());
        map.put("data",rolePageInfo.getList());
        log.info("map------------------------------------"+map);
        return map;
    }


    //宿舍查看学生
    @RequestMapping("/selDormStudent")
    @ResponseBody
    public Map<String,Object> selDormStudent(@RequestParam(required=false,defaultValue="1") int page,
                                            @RequestParam(required=false,defaultValue="7") int limit,
                                            String dormitoryId) {

        PageHelper.startPage(page, limit);
        log.info(";;;;;;;;;;;;;;;;;;;;"+dormitoryId);
        List<Student> stu = stuService.selDormStudent(dormitoryId);
        log.info("dormitoryIddormitoryIddormitoryIddormitoryId"+stu);


        for (Student i : stu) {
            i.setNativePlace(i.getNativePlace());
        }

        PageInfo<Student> pageInfo = new PageInfo<>(stu);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        log.info("mapmapmapmapmapmapmapmapmapmap" + map);
        return map;
    }

    //班级查看学生
    @RequestMapping("/selGraStudent")
    @ResponseBody
    public Map<String,Object> selGraStudent(@RequestParam(required=false,defaultValue="1") int page,
                                            @RequestParam(required=false,defaultValue="7") int limit,
                                            String gradeId){

        PageHelper.startPage(page, limit);

        List<Student> stu  = stuService.selGraStu(gradeId);// 这是我们的sql


        for(Student i:stu){
            i.setNativePlace(i.getNativePlace());
        }

        PageInfo<Student> rolePageInfo = new PageInfo<>(stu);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",rolePageInfo.getTotal());
        map.put("data",rolePageInfo.getList());
        log.info("map------------------------------------"+map);
        return map;
    }

    //跳转
    @RequestMapping("/sel")
    public String sel(){
        return "/view/stushow";
    }

}
